package com.seawaterbt.springbootshiro.aop;

import com.seawaterbt.springbootshiro.annotation.SelectDataSource;
import com.seawaterbt.springbootshiro.multiple.MultipleDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(0)
@Aspect
@Slf4j
@Component
public class MultipleDataSourceAspect {

    @Pointcut("@within(com.seawaterbt.springbootshiro.annotation.SelectDataSource) || @annotation(com.seawaterbt.springbootshiro.annotation.SelectDataSource)")
    public void pointcut(){}

    @Around("pointcut() && @annotation(dataSource)")
    public Object doAround(ProceedingJoinPoint joinPoint, SelectDataSource dataSource) throws Throwable{
        MultipleDataSource.setDataSource(dataSource.value().getName());
        try{
            return joinPoint.proceed();
        }finally {
            MultipleDataSource.remove();
        }
    }
}
